<template>
  <section>
    <ul class="template-category-list">
      <li class="category-item" v-for="(category,cIndex) in categoryList" :key="cIndex" v-if="category.deleted =='UN_DELETED'">
        <el-popover
          placement="top"
          width="160"
          v-model="category.visible">
          <p>确定删除吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="category.visible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="onItemClose(cIndex)">确定</el-button>
          </div>
          <el-button type="text" icon="el-icon-close" slot="reference" class="category-close"></el-button>
        </el-popover>
        <el-form>
          <el-form-item label="分类">
            <span>排序:</span>
            <el-input-number size="mini" style="width:50px" v-model="category.showOrder" :controls="false" :min="1" :max="99" @change="onSortChange"></el-input-number>
          </el-form-item>
          <div class="clearfix">
            <el-col :span="6">
              <el-upload class="category-uploader"
                         :action="uploadAction" :show-file-list="false"
                         :on-success="handleAvatarSuccess"
                         :before-upload="beforeAvatarUpload">
                <img v-if="category.imageUrl" :src="category.imageUrl" class="category-image" @click="onUpClick(cIndex)" />
                <i v-else class="el-icon-plus category-uploader-icon" @click="onUpClick(cIndex)"></i>
              </el-upload>
            </el-col>
            <el-col :span="18">
              <p class="default_tips">建议图片尺寸1比1，JPG、PNG格式，小于100KB</p>
              <el-form-item label="分类名称" label-width="70px">
                <el-input v-model="category.name" placeholder="输入分类名称"></el-input>
              </el-form-item>
              <el-form-item label="跳转链接">
                <el-select :ref="'category_linkUrl_'+cIndex" v-model="category.linkText" @change="onLinkChange(category,cIndex)"
                           filterable
                           allow-create
                           default-first-option placeholder="选择跳转到的页面" style="width:305px;">
                  <el-option label="书库分类" value="1"></el-option>
                  <el-option label="自定义链接可直接填写" value="2"></el-option>
                </el-select>
                <!--<el-input placeholder="选择跳转到的页面" v-model="category.linkUrl" class="input-with-select">-->
                  <!--<el-select v-model="category.linkType" slot="prepend" placeholder="请选择" style="width:90px;">-->
                    <!--<el-option label="书库" value="1"></el-option>-->
                    <!--<el-option label="自定义" value="2"></el-option>-->
                  <!--</el-select>-->
                <!--</el-input>-->
              </el-form-item>
            </el-col>
          </div>
        </el-form>
      </li>
    </ul>
    <el-row>
      <a class="category-add" @click="onItemAdd">+创建分类</a>
    </el-row>
    <el-dialog title="跳转链接" :visible.sync="dialogVisible" width="700px" @before-close="handleClose">
      <select-category @save="emitSave" v-if="dialogVisible"></select-category>
    </el-dialog>
  </section>
</template>

<script>
  import { getUploadFileRequest } from "../../../api";
import SelectCategory from './SelectCategory'
  export default {
    name: "Category",
    props:{
      categorys:{
        type:Array,
        default:[]
      }
    },
    components:{ SelectCategory },
    data(){
      return{
        categoryList:[],
        template:{
          id:null,
          bookCategoryId:'',
          showOrder:1,
          name:'',
          imageUrl:'',
          linkUrl:'',
          linkType:2,
          linkText:'',
          visible:false,
          deleted:'UN_DELETED',
        },
        uploadIndex:-1,
        uploadAction:getUploadFileRequest(),
        dialogVisible:false,
      }
    },
    watch:{
      categoryList:function (value,oldValue) {
        this.autoUpdate();
      }
    },
    methods: {
      onItemClose(index){
        this.categoryList[index].visible = false;
        if(this.categoryList[index].id != null){
          this.categoryList[index].deleted = 'DELETED';
        }else {
          this.categoryList.splice(index, 1)
        }
      },
      onItemAdd() {
        let newCategory = this.baseUtil.modelCopy(this.template);
        let list = this.categoryList.filter(m=>m.deleted=='UN_DELETED');
        let maxSort = list.length>0?list[list.length-1].showOrder : 0;
        newCategory.showOrder = maxSort + 1;
        this.categoryList.push(newCategory)
        // this.autoUpdate();
      },
      handleClose(done){
        this.uploadIndex = -1;
        done();
      },
      onLinkChange(category,index){
        switch (category.linkText) {
          case "1"://选择书库分类
            category.linkText = '';
            category.bookCategoryId = '';
            category.linkUrl = '';
            category.linkType = 1;
            this.uploadIndex = index;
            this.dialogVisible = true;
            break;
          case "2"://自定义
            category.linkText = '';
            category.linkUrl = '';
            category.bookCategoryId = '';
            category.linkType = 2;
            break;
          default://默认自定义
            category.linkType = 2;
            category.bookCategoryId = ''
            category.linkUrl = category.linkText;
            break;
        }
      },
      emitSave(category){
        this.dialogVisible = false;
        let editCategory =  this.categoryList[this.uploadIndex];
        if(category!=null){
          editCategory.bookCategoryId = category.id;
          // if(this.baseUtil.isBlank(editCategory.imageUrl)) editCategory.imageUrl=category.imageUrl;
          if(this.baseUtil.isBlank(editCategory.name)) editCategory.name = category.name;
          editCategory.linkText = category.name;
        }else{
          editCategory.linkType = 2;
        }
        this.uploadIndex = -1;
        // this.autoUpdate();
      },
      onSortChange(){
        this.categoryList.sort((a,b)=>{ return a.showOrder - b.showOrder})
      },
      onUpClick(index){
        this.uploadIndex = index;
      },
      handleAvatarSuccess(res, file) {
        this.categoryList[this.uploadIndex].imageUrl = res.data;//URL.createObjectURL(file.raw);
        this.uploadIndex = -1;
        this.autoUpdate();
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt500KB = file.size / 1024  < 500;

        if (!isJPG && !isPNG) {
          this.$message.error('分类图片只能是 JPG、PNG 格式!');
        }
        if (!isLt500KB) {
          this.$message.error('分类图片大小不能超过 500KB!');
        }
        return (isJPG||isPNG) && isLt500KB;
      },
      autoUpdate(){
        this.$emit("update:categorys",this.categoryList)
      }
    },
    mounted(){
      let categoryList = this.baseUtil.modelCopy(this.categorys)
      if(categoryList.length > 0){
        categoryList.map(m=> {
          if(m.linkType == 1) m.linkText = m.bookCategory.name;
          else m.linkText = m.linkUrl;
        });
        this.categoryList = categoryList;
      }else{
        this.categoryList = categoryList;
        this.onItemAdd();
      }
    }
  }
</script>
<style>
  .template-category-list .category-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
    width:112px;
    height:112px;
  }
  .template-category-list .category-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
<style scoped>
  .template-category-list,.template-category-list li{ list-style:none; margin:0;padding:0;}
  .template-category-list{
    width:500px;
  }
  .category-item{
    position: relative;
  }
  .category-close{
    position: absolute;
    z-index: 1001;
    right:0px;
    top:0px;
    cursor: pointer;
    font-size: 16px;
    width:16px;
    height:16px;
    color:#555;
  }
  .category-close:hover{
    color:#333;
  }
  .category-item .default_tips{
    margin:0;
    padding:0 0 10px 0;
    line-height: normal;
  }
  .category-uploader{
    margin-bottom:16px;
  }
  .category-uploader-icon {
    margin:0 auto;
    font-size: 50px;
    color: #8c939d;
    text-align: center;
    line-height: 108px;
  }
  .category-image {
    width: 112px;
    height: 112px;
    display: block;
  }
  .category-add{
    cursor: pointer;
    font-size:13px;
    font-weight: bolder;
    color:#37BCA0;
  }
</style>
